import random
import sys
import time

import redis

import controller
import utils
from slave import collect_pod_once, collect_container_once, collect_vm_once#, collect_k8s_once


def collect_slave():
    if controller.check_stop_signal():
        sys.exit(0)

    # try:
    rdb = redis.Redis(host="localhost", port=6379, db=1, decode_responses=True)
    topic = ""
    if rdb.llen("run") != 0:
        while rdb.llen("run") > 0:
            topic = rdb.rpop("run")

        print(topic)
        msgs = []
        msgs = msgs + collect_vm_once.collect_vm()
        msgs = msgs + collect_pod_once.collect_pod()
        msgs = msgs + collect_container_once.collect_container()
        # msgs = msgs + collect_k8s_once.collect_k8s()
        # time.sleep(random.random() * 1)
        # ip = controller.get_up_ip("slave")
        # utils.send_to_redis_ones(ip, msgs, topic)
        res = ""
        for msg in msgs:
            res = res + msg + " "
        rdb.rpush(topic, res)
    rdb.close()
    # except Exception:
    #     print(Exception)


def heart_beat():
    if controller.check_stop_signal():
        sys.exit(0)

    ip = controller.get_up_ip("slave")
    if ip:
        utils.set_redis_2(ip, 1, utils.get_network_ip(), 35)


def run_slave():
    t = utils.RepeatingTimer(1.0, collect_slave)
    h = utils.RepeatingTimer(10.0, heart_beat)
    t.start()
    h.start()
